package org.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class SpringBootMain {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootMain.class, args);
    }

    @Conditional({ACondition.class})
    @Bean("string")
    public String string1() {
        System.out.println("abc");
        return new String("abc");
    }

    @Conditional({BCondition.class})
    @Bean("string")
    public String string2() {
        System.out.println("123");
        return new String("123");
    }

    @ConditionalOnProperty(name = "flag", havingValue = "C", matchIfMissing = true)
    @Bean("string")
    public String string3() {
        System.out.println("456");
        return new String("456");
    }

    @ConditionalOnProperty(name = "flag", havingValue = "D")
    @Bean("string")
    public String string4() {
        System.out.println("qwe");
        return new String("qwe");
    }

    static class ACondition implements Condition {
        @Override
        public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
            Environment environment = context.getEnvironment();
            String flag = environment.getProperty("flag");
            return "A".equalsIgnoreCase(flag);
        }
    }

    static class BCondition implements Condition {
        @Override
        public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
            Environment environment = context.getEnvironment();
            String flag = environment.getProperty("flag");
            return "B".equalsIgnoreCase(flag);
        }
    }
}
